// The NSpring Framework for .NET
// Copyright (c) 2003, Jeffrey Varszegi
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without modification, 
// are permitted provided that the following conditions are met:
// 
// - Redistributions of source code must retain the above copyright notice, this 
// list of conditions and the following disclaimer.
// 
// - Redistributions in binary form must reproduce the above copyright notice, this 
// list of conditions and the following disclaimer in the documentation and/or other 
// materials provided with the distribution.
// 
// - Neither the name of the NSpring project nor the names of its contributors may 
// be used to endorse or promote products derived from this software without 
// specific prior written permission from the copyright owner.
// 
// - No product derived from this software may be called "NSpring", nor may 
// "NSpring" appear in the name of such a product, without specific prior written 
// permission from the copyright owner.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
// OF THE POSSIBILITY OF SUCH DAMAGE. 

namespace NSpring.Logging {

using System;
using System.Collections;

/// <summary>
/// The LoggerRegistry class provides access to loggers based on name.  Each LoggerRegistry
/// maintains an internal hashtable of names mapped to loggers.  A singleton instance is available
/// via the DefaultInstance property; this is also the instance used by the Logger class to provide
/// support for static methods such as AddLogger(), RemoveLogger(), and GetLogger().  The same logger may
/// be registered with multiple names, and with multiple
/// </summary>
public class LoggerRegistry 
{
    private static LoggerRegistry defaultInstance;
    private static ArrayList registries;

    private static object staticMonitor     = new object();

    private bool isCaseSensitive            = false;
    private Hashtable loggers               = new Hashtable(1000);
    private Logger[] loggersArray           = {};
    private string[] loggerNamesArray       = {};
    
    private object monitor                  = new object();

    static LoggerRegistry() 
	{
        defaultInstance = new LoggerRegistry();
        registries = new ArrayList();
        registries.Add(defaultInstance);
    }
    
    /// <summary>
    /// Gets the singleton instance of the class, which should be sufficient for most purposes.
    /// This is the same registry used by the Logger class
    /// </summary>
    public static LoggerRegistry DefaultInstance 
	{
        get { return defaultInstance; }
    }
    
    /// <summary>
    /// Constructs a new instance
    /// </summary>
    public static LoggerRegistry CreateLoggerRegistry() 
	{
        LoggerRegistry registry = new LoggerRegistry();
        lock (staticMonitor) 
		{
            registries.Add(registry);
        }
        return registry;
    }
    
    /// <summary>
    /// Gets and sets whether the registry considers names in a case-sensitive fashion; the default is false
    /// </summary>
    public bool IsCaseSensitive 
	{
        get { return isCaseSensitive; }
        set { isCaseSensitive = value; }
    }
    
    /// <summary>
    /// Adds a name-logger mapping to the registry
    /// </summary>
    /// <param name="name">The name of the logger</param>
    /// <param name="logger">The logger associated with the specified name</param>
    public void AddLogger(string name, Logger logger) 
	{
        if ((name == null) || (logger == null))
            throw new ArgumentNullException();
        name = name.Trim();
        if (!isCaseSensitive)
            name = name.ToLower();
        lock (monitor) 
		{
            if (loggers.ContainsKey(name)) 
                throw new ApplicationException("A logger is already registered with the name '" + name + '\'');
            loggers.Add(name, logger);
            loggersArray = null;
            loggerNamesArray = null;
        }
    }

    /// <summary>
    /// Removes the logger associated with the specified name from this registry
    /// </summary>
    /// <param name="name">The name for which to remove the mapping</param>
    public void RemoveLogger(string name) 
	{
        if (name == null)
            throw new ArgumentNullException();
        name = name.Trim();
        if (!isCaseSensitive)
            name = name.ToLower();
        lock (monitor) 
		{
            loggers.Remove(name);
            loggersArray = null;
            loggerNamesArray = null;
        }
    }

    /// <summary>
    /// Removes the logger, together with all names that reference it in this registry
    /// </summary>
    /// <param name="logger">The logger for which to remove all mappings</param>
    public void RemoveLogger(Logger logger) 
	{
        if (logger == null)
            throw new ArgumentNullException();
        ArrayList names = new ArrayList(20);
        string name;
        lock (monitor)
		{
            IEnumerator e = loggers.Keys.GetEnumerator();
            while (e.MoveNext())
			{
                name = (string)e.Current;
                if (loggers[name] == logger)
                    names.Add(name);
            }
            for(int x = (names.Count - 1); x >= 0; x--)
                loggers.Remove(names[x]);
            loggersArray = null;
            loggerNamesArray = null;
        }
    }
    
    /// <summary>
    /// Gets the logger associated with the given name
    /// </summary>
    /// <param name="name">The name for which to get the logger</param>
    /// <returns>The logger associated with the given name, or null if no such logger exists</returns>
    public Logger GetLogger(string name) 
	{
        if (name == null)
            throw new ArgumentNullException();
        name = name.Trim();
        if (!isCaseSensitive)
            name = name.ToLower();
        Logger logger;
        lock (monitor) 
		{
            logger = (Logger)loggers[name];
        }
        if (logger == null)
            throw new ApplicationException("No logger is registered with the name '" + name + '\'');
        return logger;
    }
    
    /// <summary>
    /// Gets an array of all loggers maintained known to this registry
    /// </summary>
    public Logger[] Loggers 
	{
        get 
		{
            lock (monitor) 
			{
                if (loggersArray == null) 
				{
                    int size = loggers.Values.Count;
                    loggersArray = new Logger[size];
                    loggers.Values.CopyTo(loggersArray, 0);
                }
                Logger[] returnValue = new Logger[loggersArray.Length];
                Array.Copy(loggersArray, 0, returnValue, 0, loggersArray.Length);
                return returnValue;
            }
        }
    }
    
    /// <summary>
    /// Gets an array of all names registered with this registry, in ascending order
    /// </summary>
    public string[] LoggerNames 
	{
        get 
		{
            lock (monitor) 
			{
                if (loggerNamesArray == null) 
				{
                    int size = loggers.Keys.Count;
                    loggerNamesArray = new string[size];
                    loggers.Keys.CopyTo(loggerNamesArray, 0);
                    Array.Sort(loggerNamesArray);
                }
                string[] returnValue = new string[loggerNamesArray.Length];
                Array.Copy(loggerNamesArray, 0, returnValue, 0, loggerNamesArray.Length);
                return returnValue;
            }
        }
    }
    
    /// <summary>
    /// Removes all name-logger mappings from this registry
    /// </summary>
    public void Clear() 
	{
        lock (monitor) 
		{
            loggers.Clear();
            loggersArray = null;
            loggerNamesArray = null;
        }
    }

	public void Open()
	{
		Logger logger;
		lock (monitor)
		{
			IEnumerator e = loggers.Values.GetEnumerator();
			while (e.MoveNext())
			{
				logger = (Logger)e.Current;
				try
				{
					logger.Open();
				}
				catch { }
			}
		}
	}

    /// <summary>
    /// Closes all loggers known to this registry, then removes their mappings.  
    /// Provided as an easy way for application-shutdown code to ensure that all loggers 
    /// are properly closed
    /// </summary>
    public void Close() 
	{
        Logger logger;
        lock (monitor) 
		{
            IEnumerator e = loggers.Values.GetEnumerator();
            while (e.MoveNext())
			{
                logger = (Logger)e.Current;
                try 
				{
                    logger.Close();
                } catch {}
            }
            loggers.Clear();
            loggersArray = new Logger[0];
            loggerNamesArray = new string[0];
        }
    }
    
    /// <summary>
    /// Calls Close() on all LoggerRegistry objects created since the start of the application
    /// </summary>
    public static void CloseAll() 
	{
        lock (staticMonitor) 
		{
            for(int x = (registries.Count - 1); x >= 0; x--)
                ((LoggerRegistry)registries[x]).Close();
        }
    }
    
}

}